<template>
  <div class="fiz-eim-login">
    <div class="fiz-eim-login-container">
      <div class="fiz-eim-logo"></div>
      <div class="fiz-eim-login-card">
        <div class="fiz-eim-login-card-head">
          <span>登录系统</span>
          <span>欢迎使用Fiz-EIM系统</span>
        </div>
        <el-form ref="formElRef" :model="params" :rules="rules" style="width: 100%">
          <el-form-item prop="username">
            <el-input
              :prefix-icon="UserFilled"
              v-model="params.username"
              placeholder="用户名"
              @keyup.enter="goLogin"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              :prefix-icon="Lock"
              v-model="params.password"
              placeholder="密码"
              @keyup.enter="goLogin"
              show-password></el-input>
          </el-form-item>
          <div class="login-operation">
            <el-checkbox
              :model-value="appStore.automaticLogon"
              @change="appStore.setAutomaticLogon"
              label="自动登录"></el-checkbox>
            <el-checkbox
              :model-value="appStore.rememberPassword"
              @change="appStore.setRememberPassword"
              label="记住密码"></el-checkbox>
          </div>
        </el-form>
        <el-button :loading="loading" class="login-btn" type="primary" @click="validate">登录</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import useApp from '@/store/app'
import { Lock, UserFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const appStore = useApp()
const loading = ref(false)

const formElRef = ref()
const params = reactive(
  JSON.parse(localStorage.getItem('login-info')) || {
    username: null,
    password: null,
  }
)

const rules = reactive({
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur',
    },
  ],
})

watch(
  params,
  (v) => {
    if (appStore.rememberPassword) {
      localStorage.setItem('login-info', JSON.stringify(v))
    } else {
      localStorage.removeItem('login-info')
    }
  },
  {
    deep: true,
  }
)

watch(
  () => appStore.rememberPassword,
  (v) => {
    if (v) {
      localStorage.setItem('login-info', JSON.stringify(params))
    } else {
      localStorage.removeItem('login-info')
    }
  }
)

function validate() {
  formElRef.value.validate((valid) => {
    if (valid) {
      goLogin()
    }
  })
}

function goLogin() {
  loading.value = true
  appStore
    .login(params)
    .then(() => {
      ElMessage.success('登录成功')
      router.push('/chat').then(() => {
        loading.value = false
      })
    })
    .catch((err) => {
      loading.value = false
      ElMessage.error('登录失败：' + err)
    })
}
</script>
